// API请求封装
const BASE_URL = process.env.VUE_APP_API_BASE_URL || (process.env.NODE_ENV === 'development' ?
	'http://localhost:3000/api' :
	'https://your-api-domain.com/api')

// 请求拦截器
const requestInterceptor = (config) => {
	// 添加认证token
	const token = uni.getStorageSync('token')
	if (token) {
		config.header = {
			...config.header,
			'Authorization': `Bearer ${token}`
		}
	}

	// 添加通用请求头
	config.header = {
		'Content-Type': 'application/json',
		...config.header
	}

	return config
}

// 响应拦截器
const responseInterceptor = (response) => {
	const {
		data,
		statusCode
	} = response

	// HTTP状态码检查
	if (statusCode !== 200) {
		throw new Error(`HTTP ${statusCode}: ${data.message || '请求失败'}`)
	}

	// 业务状态码检查
	if (!data.success) {
		// token过期，跳转到登录页
		if (data.code === 1002) {
			uni.removeStorageSync('token')
			uni.removeStorageSync('userInfo')
			uni.reLaunch({
				url: '/pages/auth/login'
			})
			throw new Error('登录已过期，请重新登录')
		}

		throw new Error(data.message || '请求失败')
	}

	// 检查是否有新token
	if (response.header['X-New-Token'] || response.header['x-new-token']) {
		const newToken = response.header['X-New-Token'] || response.header['x-new-token']
		uni.setStorageSync('token', newToken)
	}

	return data
}

// 封装请求方法
const request = (options) => {
	return new Promise((resolve, reject) => {
		// 请求拦截
		const config = requestInterceptor({
			url: BASE_URL + options.url,
			method: options.method || 'GET',
			data: options.data,
			header: options.header || {},
			timeout: options.timeout || 10000
		})

		// 打印请求详情
		console.log('=== API请求详情 ===')
		console.log('请求URL:', config.url)
		console.log('请求方法:', config.method)
		console.log('请求头:', config.header)
		console.log('请求数据:', config.data)
		console.log('BASE_URL:', BASE_URL)
		console.log('==================')

		uni.request({
			...config,
			success: (response) => {
				console.log('=== API响应详情 ===')
				console.log('响应状态:', response.statusCode)
				console.log('响应头:', response.header)
				console.log('响应数据:', response.data)
				console.log('==================')

				try {
					const result = responseInterceptor(response)
					resolve(result)
				} catch (error) {
					console.error('响应处理失败:', error)
					reject(error)
				}
			},
			fail: (error) => {
				console.error('=== API请求失败 ===')
				console.error('请求URL:', config.url)
				console.error('错误信息:', error)
				console.error('==================')

				// 网络错误处理
				if (error.errMsg.includes('timeout')) {
					reject(new Error('请求超时，请检查网络连接'))
				} else if (error.errMsg.includes('fail')) {
					reject(new Error('网络连接失败，请检查网络设置'))
				} else {
					reject(new Error(error.errMsg || '请求失败'))
				}
			}
		})
	})
}

// GET请求
export const get = (url, params = {}) => {
	const queryString = Object.keys(params)
		.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
		.join('&')

	const fullUrl = queryString ? `${url}?${queryString}` : url

	return request({
		url: fullUrl,
		method: 'GET'
	})
}

// POST请求
export const post = (url, data = {}) => {
	return request({
		url,
		method: 'POST',
		data
	})
}

// PUT请求
export const put = (url, data = {}) => {
	return request({
		url,
		method: 'PUT',
		data
	})
}

// DELETE请求
export const del = (url, data = {}) => {
	return request({
		url,
		method: 'DELETE',
		data
	})
}

// 文件上传
export const upload = (url, filePath, formData = {}) => {
	return new Promise((resolve, reject) => {
		const token = uni.getStorageSync('token')

		uni.uploadFile({
			url: BASE_URL + url,
			filePath,
			name: 'file',
			formData,
			header: {
				'Authorization': token ? `Bearer ${token}` : ''
			},
			success: (response) => {
				try {
					const data = JSON.parse(response.data)
					if (data.success) {
						resolve(data)
					} else {
						reject(new Error(data.message || '上传失败'))
					}
				} catch (error) {
					reject(new Error('响应数据解析失败'))
				}
			},
			fail: (error) => {
				console.error('上传失败:', error)
				reject(new Error(error.errMsg || '上传失败'))
			}
		})
	})
}

export default request